﻿using OSSUtility.Communicate;
using OSSUtility.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ozone.Device
{
    /// <summary>
    /// 高低温一体机
    /// </summary>
    public class DevHighorlowTemperature : DevBase
    {

        //COM
        public DevHighorlowTemperature(int CommType, string FSrvIP, int FPort) : base(CommType, FSrvIP, FPort)
        {

        }




        #region  高温


        /// <summary>
        /// 启动 开始加热循环高温机器
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public bool HeatStart()
        {

            bool temperature = false;
            try
            {
                // 开始循环 加热
                // 01 06 00 05 A0 00 E1 CB
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //寄存器地址
                ushort startAddr = 0x05;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0xA0
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }


        /// <summary>
        /// 关闭高温机器循环加热
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public bool HeatStop()
        {

            bool temperature = false;
            //关闭循环加热
            // 01 06 00 05 00 00 99 CB
            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //寄存器地址
                ushort startAddr = 0x05;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0x00
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }


        /// <summary>
        /// 设置高温机器温度
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Temp"></param>
        /// <returns></returns>
        public bool SetHeatingTemp(int Type, float Temp)
        {

            bool temperature = false;
            //将温度设定为25.0
            //01 06 00 02 00 FA A8 49
            byte[] array1 = ConvertToTwoBytes(Temp);
            try
            {
                //站点
                byte stationid = 0x01;


                //功能码
                byte funcode = 0x06;
                //寄存器地址
                ushort startAddr = 0x02;
                //发送数据
                byte[] array2 = new byte[] {

                };
                byte[] floatBytes = new byte[array1.Length + array2.Length];
                Array.Copy(array1, 0, floatBytes, 0, array1.Length);
                Array.Copy(array2, 0, floatBytes, array1.Length, array2.Length);

                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, floatBytes);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }


        public static byte[] ConvertToTwoBytes(float value, int scaleFactor = 10)
        {
            // 1. 缩放为整数
            int scaledValue = (int)(value * scaleFactor);

            // 2. 转换为两字节（大端序）
            byte[] bytes = BitConverter.GetBytes((ushort)scaledValue);
            //if (BitConverter.IsLittleEndian)
            //{
            //    Array.Reverse(bytes); // 转为大端序
            //}
            return bytes;
        }



        /// <summary>
        /// 获取高温机器物料温度
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public string GetHeatTemp()
        {

            string temperature = string.Empty;

            try
            {
                //01 03 00 00 00 08 44 0C
                //站点
                byte stationid = 0x01;

                //功能码
                byte funcode = 0x03;
                //寄存器地址
                ushort startAddr = 0x00;
                //发送数据
                byte[] array2 = new byte[] {
                    0x08,0x00
                };





                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = ParseTemperature(byteRcv).ToString();
                }
            }
            catch (Exception ex)
            {
                temperature = "";
            }
            return temperature;


        }
        #endregion




        #region   低温

        /// <summary>
        /// 设置加热温度    加热温度和冷冻温度均可设置
        /// </summary>
        /// <param name="Temp"></param>
        /// <returns></returns>
        public bool SetLowTemp(float Temp)
        {

            bool temperature = false;

            byte[] array1 = BitConverter.GetBytes(Temp);
            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x10;
                //寄存器地址
                ushort startAddr = 0x00;
                //发送数据
                byte[] array2 = new byte[] {
                    0x04,0x02,0x00
                };
                byte[] floatBytes = new byte[array1.Length + array2.Length];
                Array.Copy(array1, 0, floatBytes, 0, array1.Length);
                Array.Copy(array2, 0, floatBytes, array1.Length, array2.Length);

                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, floatBytes);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }









        /// <summary>
        /// 设置类型
        /// </summary>
        /// <param name="TempTytpe">  1 出口温度    2物料温度  咱们检测的是物料温度</param>
        /// <returns></returns>
        public bool SetLowType(int TempTytpe)
        {

            bool temperature = false;
            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x05;
                //寄存器地址
                ushort startAddr = 0x15;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0x00
                };

                if (TempTytpe == 1)
                {
                    array2 = new byte[] {
                    0x00,0x00
                };
                }

                if (TempTytpe == 2)
                {

                    array2 = new byte[] {
                    0x00,0xFF
                };
                }
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }





        /// <summary>
        /// 获取物料温度
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public string GetLowTemp()
        {

            string temperature = string.Empty;

            try
            {
                //02 03 00 06 00 02 24 39 
                //站点
                byte stationid = 0x02;


                //功能码
                byte funcode = 0x03;
                //寄存器地址
                ushort startAddr = 0x06;
                //发送数据
                byte[] array2 = new byte[] {
                    0x02,0x00
                };





                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = ParseModbusFloat(byteRcv).ToString();
                }
            }
            catch (Exception ex)
            {
                temperature = "";
            }
            return temperature;


        }











        /// <summary>
        /// 从Modbus RTU响应中解析IEEE 754单精度浮点数
        /// </summary>
        /// <param name="data">完整响应字节数组</param>
        /// <param name="offset">浮点数起始偏移量（默认3）</param>
        /// <returns>解析后的浮点数值</returns>
        public static float ParseModbusFloat(byte[] data, int offset = 3)
        {
            if (data == null || data.Length < offset + 4)
            {
                throw new ArgumentException("Invalid data length");
            }

            // Modbus RTU通常使用大端序存储浮点数
            byte[] floatBytes = new byte[4];
            floatBytes[0] = data[offset];     // 最高有效字节
            floatBytes[1] = data[offset + 1];
            floatBytes[2] = data[offset + 2];
            floatBytes[3] = data[offset + 3]; // 最低有效字节

            // 转换为浮点数（注意BitConverter默认使用小端序）
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(floatBytes);
            }

            return BitConverter.ToSingle(floatBytes, 0);
        }




        public static float ParseTemperature(byte[] responseData, int valueOffset = 5)
        {
            if (responseData == null || responseData.Length < valueOffset + 2)
            {
                throw new ArgumentException("Invalid response data length");
            }

            // 提取温度值的两个字节（大端序）
            byte highByte = responseData[valueOffset];
            byte lowByte = responseData[valueOffset + 1];

            // 组合为16位有符号整数
            short rawValue = (short)((highByte << 8) | lowByte);

            // 转换为实际温度值（示例中02 C6对应710，即71.0℃）
            return rawValue / 10.0f;
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public bool Start()
        {

            bool temperature = false;
            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x05;
                //寄存器地址
                ushort startAddr = 0x13;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0xFF
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }


        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public bool Stop()
        {

            bool temperature = false;

            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x05;
                //寄存器地址
                ushort startAddr = 0x13;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0x00
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }



        /// <summary>
        /// 允许加热
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public bool AllowHeat()
        {

            bool temperature = false;
            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x05;
                //寄存器地址
                ushort startAddr = 0x18;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0xFF
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }


        /// <summary>
        /// 制冷允许
        /// </summary>
        /// <returns></returns>
        public bool AllowRefrigeration()
        {

            bool temperature = false;
            try
            {
                //站点
                byte stationid = 0x02;
                //功能码
                byte funcode = 0x05;
                //寄存器地址
                ushort startAddr = 0x19;
                //发送数据
                byte[] array2 = new byte[] {
                    0x00,0xFF
                };
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, array2);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {
                temperature = false;
            }
            return temperature;

        }
        #endregion









    }
}
